<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.name" class="filter-item" clearable placeholder="输入部门名称搜索" size="small"
                  style="width: 200px;" @keyup.enter.native="crud.toQuery"/>
        <!--        <el-date-picker-->
        <!--          v-model="query.createTime"-->
        <!--          :default-time="['00:00:00','23:59:59']"-->
        <!--          type="daterange"-->
        <!--          range-separator=":"-->
        <!--          size="small"-->
        <!--          class="date-item"-->
        <!--          style="width: 260px;"-->
        <!--          default-value-->
        <!--          format="yyyy - MM - dd  HH:mm:ss"-->
        <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
        <!--          start-placeholder="开始日期"-->
        <!--          end-placeholder="结束日期"-->
        <!--        />-->
        <el-select v-model="query.status" class="filter-item" clearable placeholder="状态" size="small"
                   style="width: 90px" @change="crud.toQuery">
          <el-option v-for="item in enabledTypeNumberOptions" :key="item.key" :label="item.display_name"
                     :value="item.key"/>
        </el-select>
        <rrOperation :crud="crud"/>
      </div>
      <crudOperation :permission="permission"/>
    </div>
    <!--表单组件-->
    <el-dialog :before-close="crud.cancelCU" :close-on-click-modal="false" :title="crud.status.title"
               :visible.sync="crud.status.cu > 0" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" style="width: 370px;"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" style="width: 370px;"/>
        </el-form-item>
        <el-form-item v-if="form.pid !== 0" label="状态" prop="status">
          <el-switch
            v-model="form.status == 1"
            :disabled="form.id == 1"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeStatus(form, form.status,)"
          />
        </el-form-item>
        <el-form-item v-if="form.pid !== 0" label="上级部门" prop="pid">
          <treeselect v-model="form.pid" :normalizer="normalizer" :options="depts" placeholder="选择上级类目"
                      style="width: 370px;"/>
        </el-form-item>
        <el-form-item  label="部门负责人">
          <!-- <el-input v-model="form.leader" style="width: 370px;"/> -->
         <zSelect :value.sync="form.leaderUserId" :showName="form.leaderUserName"  :key="form.leaderUserName" @change="setLeaderUserId"  url="api/dropDown/sysUserList" style="width:  100%"/>
        </el-form-item>
        <el-form-item label="业务属性">
          <el-checkbox-group v-model="businessAttrNum">
            <el-checkbox
                v-for="(item,index) in dict.t_sys_dept_business_attr"
                :key="item.id"
                :value="item.value"
                :label="item.label"
                name="kmchk"
                @change="handleChange($event,item,index)"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table ref="table" v-loading="crud.loading" :data="crud.data"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}" default-expand-all row-key="id" @select="crud.selectChange"
              :normalizer="normalizer"
              @row-dblclick="crud.toEdit"
              @select-all="crud.selectAllChange" @selection-change="crud.selectionChangeHandler">
      <el-table-column :render-header="crud.renderHeader" :selectable="checkboxT" type="selection" width="60"/>
      <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('name')" label="名称" prop="name"/>
      <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('status')" align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status == 1"
              :disabled="scope.row.id === 1"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.status,)"
          />
        </template>
      </el-table-column>
      <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createTime')" label="创建日期" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('leader')" label="部门负责人" prop="leaderUserName"/>
      <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('businessAttr')" label="业务属性" prop="businessAttr">
        <template slot-scope="scope">
          <el-tag>{{ dictNameArray(dict.t_sys_dept_business_attr,scope.row.businessAttr)  }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :render-header="crud.renderHeader" v-permission="['admin','dept:edit','dept:del']" align="center" fixed="right" label="操作"
                       width="130px">
        <template slot-scope="scope">
          <udOperation
              :data="scope.row"
              :disabled-dle="scope.row.id === 1"
              :permission="permission"
              msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import crudDept from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'

// crud交由presenter持有
const defaultCrud = CRUD({title: '部门', url: 'api/sysDept', crudMethod: {...crudDept}})
const defaultForm = {id: null, name: null, pid: 1, enabled: 'true', businessAttr: '', status: '1',code:null,leaderUserId:0,leaderUserName:null}
export default {
  name: 'DesysDeptpt',
  components: {Treeselect, crudOperation, rrOperation, udOperation},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 设置数据字典
  dicts: [ 't_sys_dept_business_attr'],
  data() {
    return {
      leaderUserList:[],
      depts: [],
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入编码', trigger: 'blur'}
        ]
      },
      permission: {
        add: ['admin', 'sysDept:add'],
        edit: ['admin', 'sysDept:edit'],
        del: ['admin', 'sysDept:del'],
        import: ['admin', 'sysDept:import'],
        export: ['admin', 'sysDept:export'],
        enable: ['admin', 'sysDept:enable'],
        disable: ['admin', 'sysDept:disable'],
      },
      // business_attr: [
      //   {value: '1', label: '销售'},
      //   {value: '2', label: '采购'},
      //   {value: '3', label: '财务'},
      //   {value: '4', label: '生产'},
      //   {value: '5', label: '仓库'},
      //
      // ],
      enabledTypeOptions: [
        {key: 'true', display_name: '正常'},
        {key: 'false', display_name: '禁用'}
      ],
      enabledTypeNumberOptions: [
        {key: '1', display_name: '正常'},
        {key: '0', display_name: '禁用'}
      ],
      businessAttr: [],
      businessAttrNum: [],
    }
  },
  created() {
  },
  methods: {
    getDeptDatas(tree, treeNode, resolve) {
      const params = {pid: tree.id}
      setTimeout(() => {
        crudDept.getDepts(params).then(res => {
          resolve(res)
        })
      }, 100)
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.businessAttr!= '') {
        let list = form.businessAttr.split(',')
        let info = []
        let num = []
        this.dict.t_sys_dept_business_attr.map((item, i) => {
          list.map((res, b) => {
            if (Number(res) == item.value) {
              info.push(item.label);
              num.push(item.value);
            }
          })
        })
        this.businessAttrNum = info
        this.businessAttr = num
      } else {
        this.businessAttrNum = []
        this.businessAttr = []
      }
      if (form.pid !== null) {
        form.isTop = '0'
      } else if (form.id !== null) {
        form.isTop = '1'
      }
      if (form.id != null) {
        this.getSupDepts(form.id)
      } else {
        this.form.code= null
        this.form.pid= null
        this.getDepts()
      }
    },

    setLeaderUserId(e){
        if(!e){
          this.form.leaderUserId = 0
          this.form.leaderUserName = null
          this.form.leaderUserCode = null
        }
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    getSupDepts(id) {
      crudDept.getDepts(id).then(res => {
        const date = res
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    getDepts() {
      crudDept.getDepts({status: 1}).then(res => {
        this.depts = res.map(function (obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 获取弹窗内部门数据
    loadDepts({action, parentNode, callback}) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDept.getDepts({enabled: true, pid: parentNode.id}).then(res => {
          parentNode.children = res.map(function (obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU](crud, form) {
      if (this.form.pid !== null && this.form.pid === this.form.id) {
        this.$message({
          message: '上级部门不能为空',
          type: 'warning'
        })
        return false
      }
      this.form.businessAttr = this.businessAttr.join(',')
      if (this.form.isTop === '1') {
        this.form.pid = null
      }
      return true
    },
    // 改变状态
    changeEnabled(data, val) {
      let info = val == 0 ? '启用' : '禁止'
      this.$confirm('此操作将 "' + info + '" ' + data.name + '部门, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        data.status = val == 0 ? '1' : '0'
        crudDept.edit(data).then(res => {
          this.crud.notify(info + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.toQuery()
        }).catch(err => {
        })
      }).catch(() => {
      })
    },
    changeStatus(data, val){
      this.form.status = val == 0?1:0
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1 && !row.enabled
    },
    getSetArr(arr) {
      return [...new Set(arr)]
    },
    handleChange(event, item,index) {
      if (event) {
        this.businessAttr.push(item.value)
        // this.businessAttrNum.push(item.label)
      } else {
        this.businessAttr.splice(this.businessAttr.indexOf(item.value), 1)
        // this.businessAttrNum.splice(this.businessAttr.indexOf(item.value), 1)
      }
      this.crud.form.businessAttr = this.businessAttr.join()
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>

